package com.yc.test.distributedLock;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * @Date: 2018/11/30 18:23
 * @Author: Can.Yang
 * @Description:
 */
@Component
public class RedisLock implements Lock {

    private static final String Key = "YC_RedisLock";
    private static final int LockExpire = 1000;
    private ThreadLocal<String> localValue = new ThreadLocal<>();

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void lock() {
        if (tryLock()) {
            return;
        }
        try {
            Thread.sleep(10);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        lock();
    }

    @Override
    public boolean tryLock() {
        String uuid = UUID.randomUUID().toString();
        if (redisTemplate.getConnectionFactory().getConnection().setNX(Key.getBytes(), uuid.getBytes())) {
            redisTemplate.expire(Key, LockExpire, TimeUnit.SECONDS);
            localValue.set(uuid);
            return true;
        }
        return false;
    }

    @Override
    public void unlock() {
        if (localValue.equals(redisTemplate.opsForValue().get(Key))) {
            redisTemplate.delete(Key);
        }
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {

    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return false;
    }

    @Override
    public Condition newCondition() {
        return null;
    }
}
